<template>
  <div class="order_list">
    <van-nav-bar title="我的订单" left-text="返回" left-arrow fixed :z-index="999" @click-left="$router.push('/mine')" />

    <van-tabs sticky :active="activeIndex" :swipe-threshold="5" @click="handleTabClick" :color="CFG.colorPrimary" :title-active-color="CFG.colorPrimary">
      <van-tab v-for="tab in tabsItem" :title="tab.name" :key="tab.type"></van-tab>
    </van-tabs>

    <van-list v-model="loading" :finished="finished" :immediate-check="false" :offset="100" @load="loadMore">
      <van-panel v-for="(order, i) in items" class="order_list--panel" :key="i" :title="'订单编号: ' + order.order_number" :status="getStatusText(order.status)">
        <div>
          <van-card
            v-for="(goods, goodsI) in order.orderItems"
            class="order_list--van-card"
            :key="goodsI"
            :title="goods.title"
            :desc="pay_points(goods.pay_points)"
            :num="goods.quantity"
            :price="(goods.price / 1).toFixed(2)"
            :thumb="goods.image"
            @click.native="toOrderDetail(i)"
          >
            <div slot="footer">
              <van-button v-if="order.status == 40" size="mini" @click.stop.native="serviceAddView(goods.id, goods.quantity)">申请售后</van-button>
              <van-button v-if="order.status == 40 && goods.has_evaluate == 0" size="mini" @click.stop.native="evaluateAddView(goods.id)">评价</van-button>
              <van-button v-else-if="order.status == 40 && goods.has_evaluate == 1" disabled size="mini">已评价</van-button>
            </div>
          </van-card>

          <div class="order_list--total">
            合计:￥ {{ order.total / 1 + order.shipping_fee / 1 }}
            <span v-if="order.shipping_fee / 1 > 0">（含运费{{ order.shipping_fee }}）</span>
            <span v-else>（免运费）</span>
          </div>
        </div>
        <component slot="footer" :is="'status' + order.status" :reminder="order.is_can_reminder" @handle="actionHandle($event, i)" />
      </van-panel>
    </van-list>

    <div v-if="finished && items.length > 0" class="more">=我是有底线的=</div>

    <is-empty v-if="items.length == 0">抱歉,没有找到符合条件的订单</is-empty>
  </div>
</template>

<script>
import { Tab, Tabs, Panel, Card } from 'vant';
import IsEmpty from '@/components/include/empty';
import { Toast } from 'vant';

import status10 from '@/components/include/handle-status-10';
import status20 from '@/components/include/handle-status-20';
import status30 from '@/components/include/handle-status-30';
import status40 from '@/components/include/handle-status-40';
import status50 from '@/components/include/handle-status-50';
import status60 from '@/components/include/handle-status-60';

import loadMore from '@/components/mixin/list-load-more';

const STATUS_TEXT = {
  10: '待付款',
  20: '待发货',
  30: '待收货',
  40: '已完成',
  50: '退款成功',
  60: '交易关闭'
};

export default {
  name: 'order-lists',

  mixins: [loadMore],

  props: {
    active: {
      type: [String, Number],
      default: 1
    }
  },

  data() {
    return {
      activeIndex: this.active,
      items: [],
      tabsItem: [
        {
          name: '全部',
          status: 0
        },
        {
          name: '待付款',
          status: 10
        },
        {
          name: '待发货',
          status: 20
        },
        {
          name: '待收货',
          status: 30
        },
        {
          name: '已完成',
          status: 40
        }
      ]
    };
  },

  computed: {
    pay_points() {
      return function(val) {
        if(val > 0)
        return '使用了' + val + '积分兑换';
        else
        return '';
      };
    }
  },

  watch: {
    $route: 'resetInit'
  },

  created() {
    this.resetInit();
  },

  methods: {
    // 申请售后
    serviceAddView(order_goods_id, max_quantity) {
      this.$router.push({
        path: '/serviceAddView',
        query: {
          id: order_goods_id,
          max_quantity: max_quantity
        }
      });
    },

    // 评价
    evaluateAddView(order_goods_id) {
      this.$router.push({
        path: '/evaluateAddView',
        query: {
          id: order_goods_id
        }
      });
    },

    initData() {
      const i = this.active;
      const status = this.tabsItem[i].status;

      this.apiPost('/shop.order/lists', {
        page_size: this.pages.pageSize,
        page: this.pages.currPage,
        status
      }).then(res => {
        this.items.push(...(res.data || []));
        this.pages.listsCount = res.data.length;
        return {
          pageSize: this.pages.pageSize,
          currPage: this.pages.currPage,
          listsCount: res.data.length
        };
      });
    },

    // 删除订单
    async delOrder(i) {
      const id = this.items[i].id;
      await this.$dialog.confirm({
        message: '确定要删除该订单吗?'
      });

      // 请求服务器
      this.apiPost('/shop.order/delete', {
        order_id: this.items[i].id
      }).then(res => {
        if (res.data > 0) {
          this.items.splice(i, 1);
          this.$toast('已删除该订单');
        }
      });
    },

    // 确认收货
    async receiptOrder(i) {
      const id = this.items[i].id;
      await this.$dialog.confirm({
        message: '请确认收到货物, 确认收货后无法撤销!'
      });

      // 请求服务器
      this.apiPost('/shop.order/complete', {
        order_id: this.items[i].id
      }).then(res => {
        if (res.data > 0) {
          this.items[i].status = 40;
          this.$toast('已确认收货');
        }
      });
    },

    // 提醒发货
    reminderOrder(i) {
      const id = this.items[i].id;
      this.items[i].is_can_reminder = false;
      this.$toast('已提醒卖家发货, 请耐心等待哦~');
    },
    toPay(i) {
      const id = this.items[i].id;
      this.$router.push({
        name: 'payment',
        params: {
          order_id: id
        }
      });
    },
    handleTabClick(index) {
      this.$router.replace({
        name: 'order',
        params: {
          active: index
        }
      });
    },
    getStatusText(status) {
      return STATUS_TEXT[status] || '';
    },
    toOrderDetail(i) {
      const order_id = this.items[i].id;
      this.$router.push({
        path: '/orderViews',
        query: {
          order_id: order_id
        }
      });
    },
    actionHandle(handle, i) {
      this[handle] && this[handle](i);
    },
    // 订单轨迹
    tracker(i) {
      const order_id = this.items[i].id;
      this.$router.push({
        path: '/orderTracker',
        query: {
          order_id: order_id
        }
      });
    },
    // 调用微信JS api 支付
    jsApiCall(signature) {
      let that = this
      /* eslint-disable no-undef */
      WeixinJSBridge.invoke('getBrandWCPayRequest', signature, function(res) {
        // WeixinJSBridge.log(res.err_msg);
        // alert(JSON.stringify(res));
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          Toast('支付成功');
          that.$router.replace({ name: 'order', params: { active: 0 } });
        } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
          alert('用户取消支付');
        } else {
          alert('支付失败');
        }
      });
    },
    wxPay(index) {
      //
      const order_id = this.items[index].id;

      if (typeof WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', this.jsApiCall, false);
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', this.jsApiCall);
          document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall);
        }
      } else {
        this.apiPost('/shop.order/wx_pay_sign', {
          order_id: order_id
        }).then(res => {
          if (res.data) {
            this.jsApiCall(res.data);
          } else {
            alert('支付出现一些问题');
          }
        });
      }
    }
    // 调用微信JS api 支付 - 结束
  },
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Panel.name]: Panel,
    [Card.name]: Card,
    [IsEmpty.name]: IsEmpty,
    status10,
    status20,
    status30,
    status40,
    status50,
    status60
  }
};
</script>

<style lang="scss" scoped>
.order_list {
  padding-top: 50px;
  padding-bottom: 0;
  &--footer_btn {
    text-align: right;
  }
  &--panel {
    margin-top: 10px;
  }
  &--van-card {
    background-color: #fafafa;
  }
  &--total {
    text-align: right;
    padding: 10px;
  }
}
</style>
